<template>
  <modal-form
    v-model:form-state="formState"
    :loading="loading"
    :show="show"
    title="新建"
    width="416px"
    :rules="modelFormRules"
    @cancel="onCancel"
    @ok="onOk"
  >
    <template #default>
      <a-form-item name="name">
        <a-input v-model:value="formState.name" v-trim placeholder="请输入名称" :maxlength="200" />
      </a-form-item>
    </template>
  </modal-form>
</template>

<script setup lang="ts">
  import type { Rule } from 'ant-design-vue/es/form'
  import { ref } from 'vue'

  import { validateBitLen, validateDirName } from '@/utils'

  interface AddFormProps {
    show: boolean
    loading: boolean
  }

  withDefaults(defineProps<AddFormProps>(), {
    show: false,
    loading: false
  })

  const emits = defineEmits<{
    (e: 'update:show', value: boolean): void
    (e: 'submit', formState: FormStateType): void
  }>()

  const formState = ref({
    name: ''
  })

  type FormStateType = typeof formState

  const modelFormRules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ]
  }

  const onOk = (formState: any) => {
    emits('submit', formState)
  }

  const onCancel = () => {
    formState.value.name = ''
    emits('update:show', false)
  }

  defineExpose({
    resetForm: () => {
      formState.value.name = ''
    }
  })
</script>
